<template>
  <div class="file-list-container">
    <div class="action-bar" v-if="selectedFiles.length > 0">
      <span class="selected-count">已选中 {{ selectedFiles.length }} 个文件</span>
      <!-- 操作按钮... -->
      <el-tooltip content="转存" placement="top">
        <el-button class="action-btn" @click="moveFiles" :icon="RefreshRight"  :disabled="!selectedFiles.length">转存</el-button>
      </el-tooltip>
      <el-tooltip content="下载" placement="top">
        <el-button class="action-btn" @click="downloadFiles" :icon="Download"  :disabled="!selectedFiles.length">下载</el-button>
      </el-tooltip>
      <el-tooltip content="删除" placement="top">
        <el-button class="action-btn" @click="deleteFiles" :icon="Delete"  :disabled="!selectedFiles.length">删除</el-button>
      </el-tooltip>
      <el-tooltip content="分享" placement="top">
        <el-button class="action-btn" @click="shareFiles" :icon="Share"  :disabled="!selectedFiles.length">分享</el-button>
      </el-tooltip>
    </div>
    <!--      分享对话框组件-->
      <el-dialog title="链接分享" v-model="shareDialogVisible">
        <el-form :model="shareForm">
          <el-form-item label="文件名：">
            <div v-for="(file, index) in selectedFiles" :key="index">
              {{ file.name }}
              <span v-if="index < selectedFiles.length - 1">，</span>
            </div>
          </el-form-item>
          <el-form-item label="有效期：">
            <el-radio-group v-model="shareForm.expiry">
              <el-radio label="1天">1天</el-radio>
              <el-radio label="7天">7天</el-radio>
              <el-radio label="30天">30天</el-radio>
              <el-radio label="365天">365天</el-radio>
              <el-radio label="永久有效">永久有效</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提取码：">
            <el-radio-group v-model="shareForm.useExtractCode">
              <el-radio :value="false">系统随机生成提取码</el-radio>
              <el-radio :value="custom">自定义提取码</el-radio>
              <el-radio :value="true">无提取码</el-radio>
            </el-radio-group>
            <el-input
                v-model="shareForm.customExtractCode"
                placeholder="请输入4位提取码，仅支持数字及英文字母"
                maxlength="4"
                show-word-limit
            />
            <div v-if="shareForm.useCustomExtractCode" class="extract-code-hint">
              仅支持数字及英文字母
            </div>
          </el-form-item>
          <el-form-item label="访问人数限制：">
            <el-radio-group v-model="shareForm.useCustomAccessLimit">
              <el-radio :value="false">不限制</el-radio>
              <el-radio :value="true">自定义限制</el-radio>
            </el-radio-group>
            <el-input-number
                v-if="shareForm.useCustomAccessLimit"
                v-model="shareForm.customAccessLimit"
                :min="1"
                :max="10"
                placeholder="输入1-10人"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createShareLink">创建链接</el-button>
        </template>
      </el-dialog>
    <div class="action-bar" >
      <el-button class="action-btn" @click="uploadFile" :icon="Upload" :disabled="selectedFiles.length">上传</el-button>
      <!-- 上传对话框 -->
      <el-dialog title="上传文件" v-model="uploadDialogVisible">
        <el-upload
            ref="uploadRef"
            :on-change="handleFileChange"
            :file-list="uploadFileList"
            :show-file-list="true"
            :multiple="true"
            :drag="true"
            :auto-upload="false"
            :disabled="isUploading"
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">拖拽文件到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传多种格式文件，单个文件大小不超过 2GB
              </div>
              <div class="upload-progress" v-if="isUploading">
                <div v-for="(progress, fileName) in uploadProgress" :key="fileName">
                  <el-progress
                      :percentage="progress.percent"
                      :status="progress.percent === 100 ? 'success' : ''"
                  />
                  <div class="progress-text">
                    正在上传: {{ progress.file }}
                  </div>
                </div>
              </div>
            </template>
        </el-upload>
        <template #footer>
          <el-button @click="uploadDialogVisible = false" :disabled="isUploading" >取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="isUploading">
            {{ isUploading ? '上传中...' : '开始上传' }}
          </el-button>
        </template>
      </el-dialog>
      <el-button class="action-btn" @click="openCreateFolderDialog" :icon="Folder" :disabled="selectedFiles.length">新建文件夹</el-button>
      <!-- 创建文件夹对话框 -->
      <el-dialog title="新建文件夹" v-model="createFolderDialogVisible">
        <el-form :model="folderForm">
          <el-form-item label="文件夹名称">
            <el-input v-model="folderForm.name" placeholder="请输入文件夹名称"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="createFolderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder">确定</el-button>
        </template>
      </el-dialog>
      <div class="search-box">
        <el-input
            placeholder="搜索您的文件"
            v-model="searchQuery"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
    </div>
    <div class="breadcrumb">
      <div class="path-navigation">
<!--        <span @click="navigateTo('')" >全部文件</span>-->
<!--        <span v-for="(folder, index) in currentPathParts" :key="index">-->
<!--          / <span @click="navigateTo(folder, true)">{{ folder }}</span>-->
<!--        </span>-->
        <span v-for="(path, index) in breadcrumbs" :key="index">
        <span @click="navigateTo(path)" class="breadcrumb-item">
          {{ path }}
        </span>
      </span>
      </div>
      <span class="file-count">已全部加载，共{{ files.length }}个</span>
    </div>
    <div v-if="filteredFiles.length === 0" class="empty-folder-message">
      文件夹为空
    </div>
    <el-table
        :data="filteredFiles"
        class="file-table"
        @row-click="navigateToFile"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/> >
      <el-table-column prop="name" label="文件名" >
        <template #default="scope">
          <div class="file-row" @mouseenter="hoveredFile = scope.$index" @mouseleave="hoveredFile = -1">
            <div class="file-info-container">
              <div class="file-icon-name" :class="{ 'no-checkbox': hoveredFile !== scope.$index }">
                <el-icon :class="getFileIcon(scope.row.type)" v-if="hoveredFile !== scope.$index">
                  <component :is="getFileIcon(scope.row.type)" />
                </el-icon>
                <span>{{ scope.row.name }}</span>
              </div>
              <div class="file-actions" v-if="hoveredFile === scope.$index">
                <el-tooltip content="转存" placement="top">
                  <el-button :icon="RefreshRight" size="small" @click.stop="moveFiles([scope.row])"></el-button>
                </el-tooltip>
                <el-tooltip content="下载" placement="top">
                  <el-button :icon="Download" size="small" @click.stop="downloadFiles([scope.row])"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button :icon="Delete" size="small" @click.stop="deleteFiles([scope.row])"></el-button>
                </el-tooltip>
                <el-tooltip content="分享" placement="top">
                  <el-button :icon="Share" size="small" @click.stop="shareFiles([scope.row])"></el-button>
                </el-tooltip>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" >
        <template #default="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
     <el-table-column prop="type" label="类型" >
      <template #default="scope">
        {{ formatFileType(scope.row.type) }}
      </template>
      </el-table-column>
      <el-table-column prop="modified" label="修改日期" >
        <template #default="scope">
          {{ formatDate(scope.row.modified) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted , watch} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Upload,
  Folder,
  Download,
  Search,
  Document,
  Picture,
  VideoCamera,
  Headset,
  Delete,
  Share,
  RefreshRight
} from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute()
const router = useRouter()

const breadcrumbs = ref(['全部文件'])

// 从路由参数中解析当前路径
const currentPath = ref(route.params.path ? decodeURIComponent(route.params.path) : '');
// const currentPathParts = computed(() => {
//   // 确保路径以 '/' 开头，并且去掉末尾的 '/'
//   const path = currentPath.value ? currentPath.value.replace(/^\//, '').replace(/\/$/, '') : '';
//   return path ? path.split('/') : [];
// });


const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
const username = userInfo.username;
// const fileList = ref([])
const selectedFiles = ref([])
const hoveredFile = ref(-1) // 当前鼠标悬停的文件索引

const folderForm = ref({ name: '' })

onMounted(() => {
  // fetchFiles(username);
  // updateCurrentPath();
  const routeToType = {
    images: '图片',
    documents: '文档',
    videos: '视频',
    music: '音频',
    others:'其它',
  }
  if (route.params.type || route.params.name) {
    const fileType = routeToType[route.params.type] || route.params.name
    breadcrumbs.value = ['全部文件', fileType]
  }
})

// 从路由中获取当前路径
const updateCurrentPath = () => {
  currentPath.value = route.params.path ? decodeURIComponent(route.params.path) : '';
}

//路径导航
const navigateTo = (path, isFolder = false) => {
  if (isFolder) {
    // 如果是文件夹，追加到当前路径
    const currentPath = router.currentRoute.value.params.path || '';
    const newPath = currentPath ? `${currentPath}/${path}` : path;
    router.push({ path: `/all-files/${newPath}` });
  } else {
    // 如果是菜单项，直接跳转
    if (path === 'recycle') {
      router.push({ path: '/recycle' });
    } else if (path === 'personal') {
      router.push({ path: '/personal' });
    }else if(path === '全部文件'){
      router.push({ path: '/' });
    } else {
      router.push({ path: `/${path}` });
    }
  }
};

const navigateToFile = (file) => {
  if (file.type === 'folder') {
    navigateTo(file.name, true);
  } else{
    ElMessage.info(`打开文件: ${file.name}`);
    // 定义文件类型和路由参数的映射
    const typeToRoute = {
      image: 'images',
      document: 'documents',
      video: 'videos',
      music: 'music',
      others:'others'
    }

    const routeType = typeToRoute[file.type] || file.type
    router.push({ path: `/all-files/${routeType}` })
  }
}


//获取文件列表
// const fetchFiles = async (username) => {
//   try {
//     console.log('请求URL:', `/api/files?username=${username}`); // 打印完整URL用于调试
//     const response = await axios.get(`/api/files`, {
//       params: {username }
//     });
//     if (response.status === 200) {
//       FileList.value = response.data;
//     } else {
//       console.error('获取文件列表失败:', response.data);
//       return { files: [], folders: [] };
//     }
//   } catch (error) {
//     console.error('请求失败:', error.response ? error.response.data : error.message);
//     return { files: [], folders: [] };
//   }
// };
// //更新文件列表
// const updateFileList = async () => {
//   const data = await fetchFiles(userInfo.username,currentPath.value);
//   files.value = [...data.folders, ...data.files];
// };

const handleSelectionChange = (val) => {
  selectedFiles.value = val;
  // 更新每个文件的selected状态
  files.value.forEach(file => {
    file.selected = val.some(selectedFile => selectedFile.id === file.id)
  })
};

// 监听路由变化
watch(
    () => route.params.path,
    () => {
      updateCurrentPath()
     //updateFileList();
    }
)

const searchQuery = ref('')
const handleSearch = () => {
  // 实现搜索逻辑

}
// // 模拟文件数据
const files = ref([
  { id: 1, name: '文档1.docx', type: 'document', size: 1024 * 15, modified: '2023-05-10',path: '/user/admin'},
  { id: 2, name: '图片1.jpg', type: 'image', size: 1024 * 1024 * 2, modified: '2023-05-12' ,path: '/user/admin'},
  { id: 3, name: '视频1.mp4', type: 'video', size: 1024 * 1024 * 100, modified: '2023-05-15' ,path: '/user/admin'},
  { id: 4, name: '音频1.mp3', type: 'music', size: 1024 * 1024 * 5, modified: '2023-05-18',path: '/user/admin'},
  { id: 5, name: '文件夹1', type: 'folder', size: 0, modified: '2023-05-20' ,path: '/user/admin'},
])

// 根据路由参数过滤文件
const filteredFiles = computed(() => {
  if (route.params.type) {
    // 定义文件类型和路由参数的映射
    const routeToType = {
      images: 'image',
      documents: 'document',
      videos: 'video',
      music: 'music',
      others:'others'
    }
    const fileType = routeToType[route.params.type] || route.params.type
    return files.value.filter(file => file.type === fileType)
  }
  return files.value
})

const getFileIcon = (type) => {
  const icons = {
    document: Document,
    image:Picture,
    video:  VideoCamera,
    music: Headset,
    folder: Folder
  }
  return icons[type] || Document
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '空'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const formatFileType = (type) => {
  const typeMap = {
    document: '文档',
    image: '图片',
    video: '视频',
    music: '音频',
    folder: '文件夹',
    others: '其他'
  };
  return typeMap[type] || '未知类型';
};
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

// 上传
const uploadDialogVisible = ref(false);
const uploadFileList = ref();
const uploadRef = ref(null);
const isUploading = ref(false)
const uploadProgress = ref({})

const uploadFile = () => {
  uploadDialogVisible.value = true;
  console.log('上传文件')
}
const handleFileChange = (file, fileList) => {
  const isLt2G = file.size / 1024 / 1024 / 1024 < 2;
  if (!isLt2G) {
    ElMessage.error('上传文件大小不能超过 2GB!');
    return false;
  }
  // 将文件添加到上传列表
  uploadFileList.value = fileList
  // 初始化每个文件的上传进度
  uploadProgress.value = {};
  fileList.forEach((f) => {
    uploadProgress.value[f.name] = { percent: 0, file: f.name };
  });
  return false // 返回 false 阻止自动上传
}
// 提交上传
const submitUpload  = async () => {
  if (uploadFileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }
  isUploading.value = true

  try {
    const formData = new FormData()
    uploadFileList.value.forEach((file) => {
      formData.append('files', file.raw) //使用 file.raw 获取原始文件对象
    })

    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          uploadFileList.value.forEach((file, index) => {
            if (progressEvent.index === index) {
              uploadProgress.value[file.name] = { percent, file: file.name };
            }
          });

        }
      }
    });
    if (response.data.success) {
      ElMessage.success(`上传成功: ${response.data.message}`)
      uploadDialogVisible.value = false
      uploadFileList.value = []
      uploadProgress.value = {}
      //await updateFileList()
    } else {
      ElMessage.error(`上传失败: ${response.data.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error(`上传失败: ${error.message || '网络错误'}`)
  } finally {
    isUploading.value = false
  }
};

//新建文件夹
const openCreateFolderDialog = () => {
  createFolderDialogVisible.value = true
}
const createFolderDialogVisible = ref(false)
const createFolder = async () =>{
  if (!folderForm.value.name.trim()) {
    const timestamp = new Date().toISOString().replace(/[-:.]/g, '').slice(0, 14); // 获取当前时间格式为YYYYMMDDHHMMSS
    folderForm.value.name = `新建文件夹_${timestamp}`;
    return
  }
  const parentPath = currentPath.value; // 使用当前路径作为父路径
  try {
    const response = await axios.post('/api/createDir', {
      username,
      parentPath,
      dirName: folderForm.value.name
    });

    if (response.code === 200) {
      ElMessage.success('文件夹创建成功')
      createFolderDialogVisible.value = false
      //await updateFileList()
    } else {
      ElMessage.error('文件夹创建失败: ' + (response.data?.msg || ''))
    }
  } catch (error) {
    console.error('请求失败:', error)
    if (error.response) {
      // 服务器返回了响应，状态码不在2xx范围内
      console.error('状态码:', error.response.code);
      ElMessage.error(`文件夹创建失败: ${error.response.msg || '服务器错误'}`);
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('没有收到响应:', error.request);
      ElMessage.error('文件夹创建失败: 服务器无响应');
    } else {
      // 设置请求时出错
      console.error('请求设置错误:', error.message);
      ElMessage.error(`文件夹创建失败: ${error.message}`);
    }
  }
}

//下载方法
const downloadFiles = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请选择要下载的文件');
    return;
  }
  try {
    for (const file of selectedFiles.value) {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = `/api/download?path=${encodeURIComponent(file.path)}`;
        link.download = file.name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success(`文件 ${file.name} 下载已开始`);
    }
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(`下载失败: ${error.message}`);
  }
}

//转存
const moveFiles  = async () => {
  console.log('转存文件:', selectedFiles.value)
}

//删除
const deleteFiles = async () => {
  const count = selectedFiles.value.length

  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    const response = await axios.post('/api/delete', {
      username,
      dirName: folderForm.value.name
    });
    if (response.status === 200) {
      ElMessage.success(`已删除 ${count} 个文件`)
     // await updateFileList()
    } else {
      ElMessage.error('文件失败失败: ' + (response.data?.msg || ''))
    }
  }).catch(() => {
    // 取消操作
  })
}

//分享
const shareDialogVisible = ref(false);
const shareForm = ref({
  expiry: '7天',
  useCustomExtractCode: false,
  customExtractCode: '',
  useCustomAccessLimit: false,
  customAccessLimit: 1
});
const shareFiles = () => {
  shareDialogVisible.value=true;
}
const createShareLink = async () => {
  try {
    if (shareForm.value.useCustomExtractCode && !/^[a-zA-Z0-9]{4}$/.test(shareForm.value.customExtractCode)) {
      ElMessage.error('提取码必须为4位数字或英文字母');
      return;
    }
    for (const file of selectedFiles.value) {
      const response = await axios.post('/api/share', {
        filePath: file.path,
        expiry: shareForm.value.expiry,
        useExtractCode: shareForm.value.useCustomExtractCode,
        accessLimit: shareForm.value.customAccessLimit
      });
      if (response.status === 200) {
        ElMessage.success(`分享链接生成成功`)
      } else {
        ElMessage.error(`分享链接生成失败` + (response.data?.msg || ''))
      }
      console.log('分享链接生成请求发送', shareForm.value);
      shareDialogVisible.value = false;
    }
  }catch(error){
    console.error('分享链接生成失败:', error);
  }
};
</script>

<style scoped>
.file-list-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.action-btn {
  padding: 8px 15px;
  margin-right: 10px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-btn:hover {
  background-color: #2980b9;
}

.search-box {
  margin-left: auto;
  margin-right: 20px;
  width: 200px;
}

.search-box input {
  width: 100%;
  padding: 8px 15px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}
.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.path-navigation{
  color: #666;
}
.file-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}
.file-count {
  margin-left: auto;
  color: #666;
}

.file-table {
  width: 100%;
  table-layout: fixed; /* 确保表格列宽固定 */
}

.file-table .el-table__header th,
.file-table .el-table__body td {
  width: 33.33%; /* 将列宽设置为均分 */
  text-align: left;
  padding: 10px;
  word-break: break-word; /* 确保长文本不会破坏布局 */
}

.file-table tr:hover {
  background-color: #c7dfef;
}
.empty-folder-message {
  text-align: center;
  color: #999;
  font-size: 16px;
  margin-top: 20px;
}

.file-info-container {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.file-icon-name {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-grow: 1; /* 占据剩余空间 */
}

.file-icon-name.no-checkbox {
  margin-left: 8px; /* 当没有复选框时调整左边距 */
  display: flex;
  align-items: center;
  gap: 8px;
  flex-grow: 1;
}
.file-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: auto; /* 将操作按钮推到最右侧 */
}
.selected-count {
  margin-right: 20px;
  color: #666;
}
</style>